/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.terramagnet.mvcframework.resource.thumbnails;

import org.terramagnet.mvcframework.resource.ResourceArchive;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terramagnet.mvcframework.ApplicationRuntimeException;

/**
 * 自定义大小的缩略图.
 *
 * @author terrason
 */
public class DimensionThumbnails {

    private final Logger logger = LoggerFactory.getLogger(DimensionThumbnails.class);

    public ResourceArchive toThumbmails(final ResourceArchive resource, final Dimension dimension) {
        DimensionRename rename = new DimensionRename(dimension);
        String newname = rename.apply(resource.getUrl(), null);
        String thumbFileName = rename.apply(resource.getFile().getAbsolutePath(), null);
        final File thumbFile = new File(thumbFileName);

        if (thumbFile.exists()) {
            logger.debug("缩略图已存在，不再重新创建：{}", thumbFile);
        } else {
            makeThumbnail(resource, dimension, thumbFile);
        }
        return new ResourceArchive(thumbFile, newname);
    }

    private void makeThumbnail(ResourceArchive resource, Dimension dimension, File thumbFile) {
        try {
            Thumbnails.of(resource.getFile())
                .size(dimension.width, dimension.height)
                .toFile(thumbFile);
            logger.debug("创建缩略图文件：{}", thumbFile.getAbsoluteFile());
        } catch (IOException ex) {
            throw new ApplicationRuntimeException("生成缩略图出错", ex);
        }
    }
}
